import {
	HTTP_REQUEST_URL,
	HEADER,
	TOKENNAME
} from '@/config/app';
import $store from "../store";
import {
	getPage
} from '@/lib/Comment.js'

function toLogin() {
	if ($store.getters.currentLogin) return

	$store.commit('LOGOUT');
	$store.commit("SETBACKLOGIN", true)
	//	$store.state.backUrl = getPage()


	let pages = getCurrentPages();
	let curPage = pages[pages.length - 1];
	let route = curPage.route;
	let curParam = curPage.options || curPage.$route.query;
	if (curParam && Object.keys(curParam).length > 0) {
		let url = '';
		for (let i in curParam) {
			url += "&" + i + "=" + curParam[i]
		}
		url = url.substr(1)
		route = route + '?' + url
	}

	console.log('>>>>>>>>>page', route)
	$store.dispatch("SETBACKURL", route).then(res => {
		console.log("?router????", res)
		uni.navigateTo({
			url: "/pages/login/h5Login"
		})
	});

}

function toAuth() {
	uni.navigateTo({
		url: "/pages/login/auth"
	})
}


function toFrozen() {
	$store.commit("LOGOUT");
	uni.navigateTo({
		url: "/pages/login/frozen"
	})
}


/**
 * 发送请求
 */
function baseRequest(url, method, data, {
	noAuth = false,
	noVerify = false
}) {
	let Url = HTTP_REQUEST_URL,
		header = JSON.parse(JSON.stringify(HEADER));

	return new Promise((reslove, reject) => {
		if (!noAuth) {
			if (!$store.getters.isLogin && !noVerify) {
				console.log('..url', url)
				toLogin();
				reject("请登录");
				return
			}
			//console.log(url, $store.getters.isLogin, $store.getters.token)
			if ($store.getters.isLogin)
				header["Authori-zation"] = $store.getters.token;

		}

		uni.request({
			url: Url + '/' + url,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: (res) => {

				if (noVerify)
					reslove(res.data, res);
				else if (res.data.code == 200)
					reslove(res.data, res);
				else if ([401].indexOf(res.data.code) !== -1) {
					toLogin();
					reject(res.data);
				} else if ([402].indexOf(res.data.code) !== -1) {
					toAuth();
					reject(res.data);
				} else if ([409].indexOf(res.data.code) !== -1) {
					toFrozen();
					reject(res.data);
				} else {
					uni.showToast({

						title: res.data.message,
						icon: 'none',
						duration: 3000
					});
					reject(res.data.message || '系统错误', 400);
				}
			},
			fail: (msg) => {
				reject('请求失败');
			}
		})
	});
}

const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
});



export default request;